package com.example.myapplication.part9;

import android.os.Bundle;

import androidx.activity.EdgeToEdge;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.Settings;
import android.speech.RecognizerIntent;
import android.speech.tts.TextToSpeech;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import java.util.ArrayList;
import java.util.Locale;

import com.example.myapplication.R;

public class LoginActivity extends AppCompatActivity {
    private static final int REQ_CODE_ACCOUNT = 101;
    private static final int REQ_CODE_PASSWORD = 102;
    private static final int PERM_REQ_CODE = 201;
    // UI组件
    private EditText etAccount, etPassword;
    private TextToSpeech ttsEngine;
    private int activeInputType = REQ_CODE_ACCOUNT;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
// 初始化组件
        initializeUIComponents();
// 检查麦克风硬件
        checkMicrophoneAvailability();
// 初始化TTS引擎
        initializeTTS();
    }

    private void initializeUIComponents() {
        etAccount = findViewById(R.id.login_id);
        etPassword = findViewById(R.id.login_password);
        ImageButton btnVoiceAccount = findViewById(R.id.btn_voice_account);
        ImageButton btnVoicePassword = findViewById(R.id.btn_voice_password);
        Button btnLogin = findViewById(R.id.login_button);
// 语音输入按钮监听
        btnVoiceAccount.setOnClickListener(v -> {
            activeInputType = REQ_CODE_ACCOUNT;
            handleVoiceInput();
        });
        btnVoicePassword.setOnClickListener(v -> {
            activeInputType = REQ_CODE_PASSWORD;
            handleVoiceInput();
        });
// 登录按钮监听
        btnLogin.setOnClickListener(v -> validateLogin());
    }

    private void checkMicrophoneAvailability() {
        if
        (!getPackageManager().hasSystemFeature(PackageManager.FEATURE_MICROPHONE)) {
            Toast.makeText(this, "设备不支持麦克风功能", Toast.LENGTH_LONG).show();
            findViewById(R.id.btn_voice_account).setEnabled(false);
            findViewById(R.id.btn_voice_password).setEnabled(false);
        }
    }

    private void handleVoiceInput() {
        if (checkPermission()) {
            startVoiceRecognition();
        } else {
            requestPermissionWithValidation();
        }
    }

    private boolean checkPermission() {
        return ContextCompat.checkSelfPermission(this,
                Manifest.permission.RECORD_AUDIO)
                == PackageManager.PERMISSION_GRANTED;
    }

    private void requestPermissionWithValidation() {
        if (ActivityCompat.shouldShowRequestPermissionRationale(this,
                Manifest.permission.RECORD_AUDIO)) {
            showRationaleDialog();
        } else {
            ActivityCompat.requestPermissions(
                    this,
                    new String[]{Manifest.permission.RECORD_AUDIO},
                    PERM_REQ_CODE
            );
        }
    }

    private void showRationaleDialog() {
        new AlertDialog.Builder(this)
                .setTitle("需要麦克风权限")
                .setMessage("此功能需要访问麦克风以进行语音输入")
                .setPositiveButton("允许", (d, w) -> requestAudioPermission())
                .setNegativeButton("拒绝", null)
                .show();
    }

    private void requestAudioPermission() {
        ActivityCompat.requestPermissions(
                this,
                new String[]{Manifest.permission.RECORD_AUDIO},
                PERM_REQ_CODE
        );
    }

    private void startVoiceRecognition() {
        Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
        intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,
                RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
        intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE, Locale.getDefault());
        intent.putExtra(RecognizerIntent.EXTRA_PROMPT, "请开始说话");
        try {
            startActivityForResult(intent, activeInputType);
        } catch (Exception e) {
            Toast.makeText(this, "语音输入功能不可用", Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK && data != null) {
            ArrayList<String> results =
                    data.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);
            if (results != null && !results.isEmpty()) {
                updateInputFields(requestCode, results.get(0));
            }
        }
    }

    private void updateInputFields(int requestCode, String recognizedText) {
        if (requestCode == REQ_CODE_ACCOUNT) {
            etAccount.setText(recognizedText);
        } else if (requestCode == REQ_CODE_PASSWORD) {
            etPassword.setText(recognizedText);
        }
    }

    private void initializeTTS() {
        ttsEngine = new TextToSpeech(this, status -> {
            if (status == TextToSpeech.SUCCESS) {
                int result = ttsEngine.setLanguage(Locale.CHINA);
                if (result == TextToSpeech.LANG_MISSING_DATA || result ==
                        TextToSpeech.LANG_NOT_SUPPORTED) {
                    Toast.makeText(this, "中文语音包不可用",
                            Toast.LENGTH_SHORT).show();
                }
            }
        });
    }

    private void validateLogin() {
        String account = etAccount.getText().toString().trim();
        String password = etPassword.getText().toString().trim();
        if (account.isEmpty() || password.isEmpty()) {
            speakFeedback("请输入完整的登录信息");
        }

        //ttsEngine.speak("登录验证成功", TextToSpeech.QUEUE_FLUSH, null, null);
        ttsEngine.speak(account+password, TextToSpeech.QUEUE_FLUSH, null, "utteranceId");
    }

    private void performLogin(String account, String password) {
        speakFeedback("正在验证登录信息...");
// 实际登录逻辑实现
    }

    private void speakFeedback(String message) {
        if (ttsEngine != null) {
            ttsEngine.speak(message, TextToSpeech.QUEUE_FLUSH, null, null);
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[]
            permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == PERM_REQ_CODE) {
            handlePermissionResult(grantResults);
        }
    }

    private void handlePermissionResult(int[] grantResults) {
        if (grantResults.length > 0 && grantResults[0] ==
                PackageManager.PERMISSION_GRANTED) {
            startVoiceRecognition();
        } else {
            handlePermissionDenial();
        }
    }

    private void handlePermissionDenial() {
        if (ActivityCompat.shouldShowRequestPermissionRationale(this,
                Manifest.permission.RECORD_AUDIO)) {
            showReRequestDialog();
        } else {
            showPermanentDenialDialog();
        }
    }

    private void showReRequestDialog() {
        new AlertDialog.Builder(this)
                .setTitle("权限需要")
                .setMessage("需要麦克风权限才能使用语音输入")
                .setPositiveButton("再次请求", (d, w) -> requestAudioPermission())
                .setNegativeButton("取消", null)
                .show();
    }

    private void showPermanentDenialDialog() {
        new AlertDialog.Builder(this)
                .setTitle("权限被永久拒绝")
                .setMessage("请到应用设置中手动开启权限")
                .setPositiveButton("去设置", (d, w) -> openAppSettings())
                .setCancelable(false)
                .show();
    }

    private void openAppSettings() {
        try {
// 标准Android设置
            Intent intent = new
                    Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
            intent.setData(Uri.parse("package:" + getPackageName()));
            startActivity(intent);
        } catch (Exception e) {
// 处理厂商定制系统
            try {
// 小米设备
                Intent miuiIntent = new
                        Intent("miui.intent.action.APP_PERM_EDITOR");
                miuiIntent.setClassName("com.miui.securitycenter",
                        "com.miui.permcenter.permissions.PermissionsEditorActivity");
                miuiIntent.putExtra("extra_pkgname", getPackageName());
                startActivity(miuiIntent);
            } catch (Exception ex) {
                try {
// 华为设备
                    // Intent huaweiIntent = new Intent("com.huawei.systemmanager", "com.huawei.permissionmanager.ui.MainActivity");
                    // startActivity(huaweiIntent);
                } catch (Exception ex2) {
// 通用回退
                    startActivity(new Intent(Settings.ACTION_SETTINGS));
                }
            }
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (ttsEngine != null) {
            ttsEngine.stop();
            ttsEngine.shutdown();
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
// 从设置返回时检查权限状态
        if (checkPermission()) {
            findViewById(R.id.btn_voice_account).setEnabled(true);
            findViewById(R.id.btn_voice_password).setEnabled(true);
        }
    }
}